package jian.thread.newbie;

/**
 * 测试线程间的通信<br>
 * 子线程循环10次, 主线程循环100次, 如此循环100次<br>
 * 
 * @author Jian
 * @date 2013-06-19
 * 
 */
public class TestThreadCommunicate {

	public static void main(String[] args) {
		final Runner runner = new Runner();
		new Thread(new Runnable() {
			@Override
			public void run() {
				execute(runner, "sub");
			}
		}).start();
		execute(runner, "main");
	}

	private static void execute(Runner runner, String threadType) {
		for (int i = 0; i < 3; i++) {
			if (threadType.equals("main")) {
				runner.runMain(i);
			} else if (threadType.equals("sub")) {
				runner.runSub(i);
			}
		}
	}
}

class Runner {

	private boolean isChanged;

	public synchronized void runMain(int loopIndex) {
		while (!isChanged) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		for (int i = 0; i < 10; i++) {
			System.out.println("【Main】" + Thread.currentThread().getName()
					+ " : loop ->" + loopIndex + "-" + i);
		}
		isChanged = false;
		notify();
	}

	public synchronized void runSub(int loopIndex) {

		while (isChanged) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		for (int i = 0; i < 5; i++) {
			System.out.println("【Sub】" + Thread.currentThread().getName()
					+ " : loop ->" + loopIndex + "-" + i);
		}
		isChanged = true;
		notify();
	}
}
